package net.app.zoneland.controller;

import cn.hutool.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * @Description
 * @Author LENOVO
 * @CreateTime 2021/2/2 14:32
 * @Version: 1.0
 */
@RestController
public class AddrController {

    @RequestMapping("/index")
    public String getIndex(HttpServletRequest request){
        String ipaddre = getIpAddress(request);
        System.out.println(ipaddre);
        AddressUtils addressUtils = new AddressUtils();
        String address = "";
        try {
            address = addressUtils.getAddresses("ip=" + ipaddre, "utf-8");


            System.out.println("获取的地址为：" + address);

        }
        catch (UnsupportedEncodingException e) {
            System.out.println("获取用户Ip信息失败");
        }
        return address;
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
